package com.liyu.rabbit.producer;

import com.liyu.rabbit.factory.RabbitFactory;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.rabbitmq.client.MessageProperties;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author 李誉
 * @date 2022-05-22 16:15
 * @description 直连交换机 生产者示例代码
 */
public class DirectProducer {

    public static final String directExchange = "direct_ex";

    public static final String helloQueue = "hello";

    public static final String helloQueue2 = "hello2";

    public static void main(String[] args) throws Exception {
        // 创建信道
        Channel channel = RabbitFactory.createNewChannel();
        // 开启发布确认
        channel.confirmSelect();

        // 添加发布确认监听
        ConfirmCallback ack = (deliveryTag, multiple) -> {
            System.out.println("消息" + deliveryTag + "发布成功。");
        };
        ConfirmCallback nack = (deliveryTag, multiple) -> {
            System.out.println("消息" + deliveryTag + "发布失败。");
        };
        channel.addConfirmListener( ack, nack);

        // 声明直连交换机
        channel.exchangeDeclare(directExchange, BuiltinExchangeType.DIRECT);

        // 声明队列: 队列名称， 是否持久化， 是否独占， 是否自动删除， 其他参数
        channel.queueDeclare(helloQueue, true, false,  false, null);
        channel.queueDeclare(helloQueue2, true, false, false, null);

        // 建立交换机和路由绑定关系
        channel.queueBind(helloQueue, directExchange, "rk_" + helloQueue);
        channel.queueBind(helloQueue2, directExchange, "rk_" + helloQueue2);

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入路由key:");
        String routingKey = null;
        String msg = null;
        while (scanner.hasNext()) {
            routingKey = scanner.next();
            if (routingKey == null || "".equals(routingKey)) {
                continue;
            }
            System.out.println("请输入发送的消息");
            msg = scanner.next();

            channel.basicPublish(directExchange,routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes(StandardCharsets.UTF_8));

            System.out.println("请输入路由key:");
        }
    }
}
